/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.Controller;

import com.aptech.DAO.userDAO;
import com.aptech.model.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class userLogin extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        User objUser = (User) form;
        User user = null;
        try {
            String userPass = objUser.getUserPassword();
            String passMd5 = addUser.encodeMD5(userPass);
            objUser.setUserPassword(passMd5);
            userDAO userDao = new userDAO();
            user = userDao.login(objUser);
            if (user != null) {
                HttpSession session = request.getSession(true);
                session.setAttribute("user", user);
                return mapping.findForward(SUCCESS);
            } else {
                 HttpSession session = request.getSession(true);
                session.setAttribute("loginFail", objUser);
                response.sendRedirect("login.jsp");
                return mapping.findForward("Khong dc!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return mapping.findForward(ERROR);
        }
    }

    public static String encodeMD5(String str) {
        String res = "";

        try {
            org.apache.commons.codec.digest.DigestUtils digestUtil = new DigestUtils();
            res = digestUtil.md5Hex(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return res;
    }
}
